//
//  SMImagePickerController.m
//  cherryproduct
//
//  Created by zou shigang on 14/8/30.
//  Copyright (c) 2014年 cherry. All rights reserved.
//

#import "SMImagePickerController.h"
#import <AssetsLibrary/AssetsLibrary.h>

#define ADD_GROUP_PICKER_CELL @"ADD_GROUP_PICKER_CELL"

@interface SMImagePickerController ()<UIAlertViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate>
{
    BOOL isStatic;
    BOOL hasBlur;
    NSInteger selectedFilter;
    
//    ALAssetsLibrary * assetsLibrary_for_url;
    //是否前置摄像头
    BOOL m_is_front;
    UICollectionView * m_collectionView;
    
    BOOL m_isCameraValid_NO;
}

@end

@implementation SMImagePickerController

//- (NSMutableArray*)array_select
//{
//    if (_array_select==nil) {
//        _array_select =[[NSMutableArray alloc] initWithCapacity:8];
//    }
//    return _array_select;
//}

- (GPUImageView *)imageFilter
{
    if (_imageFilter==nil) {
        _imageFilter = [[GPUImageView alloc] initWithFrame:self.view.frame];
        [self.view addSubview:_imageFilter];
    }
    return _imageFilter;
}

- (UIScrollView*)scollview_filter_btn
{
    if (_scollview_filter_btn == nil) {
        _scollview_filter_btn=[[UIScrollView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height-80-61, self.view.frame.size.width, 80)];
        
        UIView * view_bg = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height-80-61, self.view.frame.size.width, 80)];
        view_bg.backgroundColor=[UIColor blackColor];
        view_bg.alpha=0.5;
        [self.view addSubview:view_bg];
        
        [self.view addSubview:_scollview_filter_btn];
    }
    return _scollview_filter_btn;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationNone];
    
    [self addNoticeStop];
    
    if (stillCamera) {
        [stillCamera startCameraCapture];
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [self subNoticeStop];
    
    if (stillCamera) {
        [stillCamera stopCameraCapture];
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor blackColor];
    // Do any additional setup after loading the view.
    {
        [self initViewSome];
        // Do any additional setup after loading the view.
        self.imageFilter.fillMode = kGPUImageFillModePreserveAspectRatioAndFill;
        //zsg
        //[self loadFilters];
        
        //we need a crop filter for the live video
        cropFilter = [[GPUImageCropFilter alloc] init];
        filter = [[GPUImageRGBFilter alloc] init];
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
            [self setUpCamera];
        });
    }
}

-(void) dealloc {
    [self removeAllTargets];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)addNoticeStop
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(doStop:)
                                                 name:K_Cancem_Notification
                                               object:nil];
}
- (void)subNoticeStop
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:K_Cancem_Notification object:nil];
}
- (void)doStop:(NSNotification *)sender
{
    NSNumber * b = [[sender userInfo] objectForKey:@"id"];
    if ([b intValue]==0) {
        [stillCamera stopCameraCapture];
    } else {
        [stillCamera startCameraCapture];
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark -
#pragma mark selfMethod
- (void)initViewSome
{
    self.view.backgroundColor=[UIColor blackColor];
    //self.myView.backgroundColor=[UIColor blackColor];
    
    if (_imageFilter==nil) {
        _imageFilter = [[GPUImageView alloc] initWithFrame:self.view.frame];
        [self.view addSubview:_imageFilter];
    }
    /*
    if (_scollview_filter_btn == nil) {
        _scollview_filter_btn=[[UIScrollView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height-80-61, self.view.frame.size.width, 80)];
        
        UIView * view_bg = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height-80-61, self.view.frame.size.width, 80)];
        view_bg.backgroundColor=[UIColor blackColor];
        view_bg.alpha=0.5;
        [self.view addSubview:view_bg];
        
        [self.view addSubview:_scollview_filter_btn];
    }*/
    
    UIView * view_toolTop = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 64)];
    view_toolTop.backgroundColor=[UIColor clearColor];
    UIView * view_b = [[UIView alloc] initWithFrame:view_toolTop.frame];
    view_b.backgroundColor=[UIColor blackColor];
    view_b.alpha=0.4;
    [view_toolTop addSubview:view_b];
    [self.view addSubview:view_toolTop];
    
    UIButton * button_check = [UIButton buttonWithType:UIButtonTypeCustom];//106 × 122
    button_check.frame=CGRectMake(self.view.frame.size.width-100, 0, 100, 64);
    [button_check setImage:[UIImage imageNamed:@"front-camera.png"] forState:UIControlStateNormal];
    [button_check addTarget:self action:@selector(doActionChangeFace:) forControlEvents:UIControlEventTouchUpInside];
    [view_toolTop addSubview:button_check];
    
    //相册列表
    if (m_collectionView==nil) {
        UICollectionViewFlowLayout * layout= [[UICollectionViewFlowLayout alloc] init];
        [layout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
        [layout setItemSize:CGSizeMake(35, 35)]; //设置每个cell显示数据的宽和高必须
        layout.sectionInset = UIEdgeInsetsMake(0, 5, 0, 0);
        layout.minimumLineSpacing=5;
        layout.minimumInteritemSpacing=0;
        
        m_collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width-105, 64) collectionViewLayout:layout];
        m_collectionView.backgroundColor=[UIColor clearColor];
        m_collectionView.delegate=self;
        m_collectionView.dataSource=self;
        
        [m_collectionView registerClass:[AlbumAddImageCell class] forCellWithReuseIdentifier:ADD_GROUP_PICKER_CELL];
        
        [view_toolTop addSubview:m_collectionView];
    }
    
    //...
    UIView * view_toolBase = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height-61, self.view.frame.size.width, 61)];
    view_toolBase.backgroundColor=[UIColor clearColor];
    view_b = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 61)];
    view_b.backgroundColor=[UIColor blackColor];
    view_b.alpha=0.4;
    [view_toolBase addSubview:view_b];
    [self.view addSubview:view_toolBase];
    
    UIButton * button_action = [UIButton buttonWithType:UIButtonTypeCustom];//106 × 122
    button_action.frame=CGRectMake((self.view.frame.size.width-53)/2, 0, 53, 61);
    [button_action setImage:[UIImage imageNamed:@"camera.png"] forState:UIControlStateNormal];
    [button_action addTarget:self action:@selector(doActionPicture:) forControlEvents:UIControlEventTouchUpInside];
    [view_toolBase addSubview:button_action];
    
    UIButton * button_back = [UIButton buttonWithType:UIButtonTypeCustom];//54 × 60
    button_back.frame = CGRectMake(0, 0, 100, 61);
    [button_back setImage:[UIImage imageNamed:@"camera_off.png"] forState:UIControlStateNormal];
    [button_back setImage:[UIImage imageNamed:@"camera_off_press.png"] forState:UIControlStateHighlighted];
    [button_back addTarget:self action:@selector(doActionClose:) forControlEvents:UIControlEventTouchUpInside];
    [view_toolBase addSubview:button_back];
    
    UIButton * button_sender = [UIButton buttonWithType:UIButtonTypeCustom];//54 × 60
    button_sender.frame = CGRectMake(self.view.frame.size.width-100, 0, 100, 61);
    [button_sender setImage:[UIImage imageNamed:@"camera_ok.png"] forState:UIControlStateNormal];
    [button_sender setImage:[UIImage imageNamed:@"camera_ok.png"] forState:UIControlStateHighlighted];
    [button_sender addTarget:self action:@selector(doActionSender:) forControlEvents:UIControlEventTouchUpInside];
    [view_toolBase addSubview:button_sender];
    
    //new:add
//    if (self.m_is_xuan_hd) {
//        button_sender.hidden=YES;
//    }
}

#pragma mark -
#pragma mark self method
-(void) setUpCamera {
    if ([[UIDevice currentDevice].systemVersion doubleValue] >= 7.0) {//判断相机是否关闭权限
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if (authStatus == AVAuthorizationStatusDenied)
        {
            m_isCameraValid_NO = YES;
            
            dispatch_async(dispatch_get_main_queue(), ^{
                UIAlertView * alert_show = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"程序无访问相机权限(设置>隐私>相机,请进行设置)" delegate:nil cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
                [alert_show show];
            });
            
            // No camera
            NSLog(@"No camera");
            runOnMainQueueWithoutDeadlocking(^{
                [self prepareFilter];
            });
            
            return;
        }
    }
    
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        // Has camera
        stillCamera = [[GPUImageStillCamera alloc] initWithSessionPreset:AVCaptureSessionPreset640x480
                                                          cameraPosition:AVCaptureDevicePositionBack];
        stillCamera.outputImageOrientation = UIInterfaceOrientationPortrait;
        
        runOnMainQueueWithoutDeadlocking(^{
            [stillCamera startCameraCapture];
            [self prepareFilter];
        });
    } else {
        // No camera
        NSLog(@"No camera");
        runOnMainQueueWithoutDeadlocking(^{
            [self prepareFilter];
        });
    }
    
}
-(void) loadFilters {
    for(int i = 0; i < 10; i++) {
        UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setImage:[UIImage imageNamed:[NSString stringWithFormat:@"style_%d.png", i + 1]] forState:UIControlStateNormal];
        button.frame = CGRectMake(10+i*(60+10), 2.0f, 60.0f, 79.0f);
        
        [button addTarget:self action:@selector(filterClicked:) forControlEvents:UIControlEventTouchUpInside];
        button.tag = i;
        
        [button setImage:[UIImage imageNamed:[NSString stringWithFormat:@"style_%d_selected.png", i + 1]] forState:UIControlStateSelected];
        if (i == 0){
            [button setSelected:YES];
        }
		[self.scollview_filter_btn addSubview:button];
	}
	[self.scollview_filter_btn setContentSize:CGSizeMake(10 + 10*(60+10), 80.0)];
}
-(void) removeAllTargets {
    [stillCamera removeAllTargets];
    [staticPicture removeAllTargets];
    [cropFilter removeAllTargets];
    
    //regular filter
    [filter removeAllTargets];
    
    //blur
    [blurFilter removeAllTargets];
}
- (void)filterClicked:(UIButton *)sender
{
    for(UIView *view in self.scollview_filter_btn.subviews){
        if([view isKindOfClass:[UIButton class]]){
            [(UIButton *)view setSelected:NO];
        }
    }
    
    [sender setSelected:YES];
    [self removeAllTargets];
    
    selectedFilter = sender.tag;
    [self setFilter:sender.tag];
    [self prepareFilter];
}
-(void) setFilter:(NSInteger) index {
    if (filter) {
        //[filter release];
    }
    switch (index) {
        case 1:{
            filter = [[GPUImageContrastFilter alloc] init];
            [(GPUImageContrastFilter *) filter setContrast:1.75];
        } break;
        case 2: {
            filter = [[GPUImageToneCurveFilter alloc] initWithACV:@"crossprocess"];
        } break;
        case 3: {
            filter = [[GPUImageToneCurveFilter alloc] initWithACV:@"02"];
        } break;
        case 4: {
            filter = [[GrayscaleContrastFilter alloc] init];
        } break;
        case 5: {
            filter = [[GPUImageToneCurveFilter alloc] initWithACV:@"17"];
        } break;
        case 6: {
            filter = [[GPUImageToneCurveFilter alloc] initWithACV:@"aqua"];
        } break;
        case 7: {
            filter = [[GPUImageToneCurveFilter alloc] initWithACV:@"yellow-red"];
        } break;
        case 8: {
            filter = [[GPUImageToneCurveFilter alloc] initWithACV:@"06"];
        } break;
        case 9: {
            filter = [[GPUImageToneCurveFilter alloc] initWithACV:@"purple-green"];
        } break;
        default:
            filter = [[GPUImageRGBFilter alloc] init];
            break;
    }
    //前置要反
    if (m_is_front) {
        [self.imageFilter setInputRotation:kGPUImageFlipHorizonal atIndex:0];
    }
}
-(void) prepareFilter {
    if (![UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        isStatic = YES;
    }
    
    if (m_isCameraValid_NO) {//ios7 没有打开相机
        [self prepareStaticFilter];
        return;
    }
    
    if (!isStatic) {
        [self prepareLiveFilter];
    } else {
        [self prepareStaticFilter];
    }
}
-(void) prepareLiveFilter {
    
    [stillCamera addTarget:cropFilter];
    [cropFilter addTarget:filter];
    //blur is terminal filter
    if (hasBlur) {
        [filter addTarget:blurFilter];
        [blurFilter addTarget:self.imageFilter];
        //regular filter is terminal
    } else {
        [filter addTarget:self.imageFilter];
    }
    [filter prepareForImageCapture];
}
-(void) prepareStaticFilter
{
    if (!staticPicture) {
        NSLog(@"Creating new static picture");
        //[self.photoCaptureButton setTitle:@"Save" forState:UIControlStateNormal];
        UIImage *inputImage = [UIImage imageNamed:@"Sample.jpg"];
        staticPicture = [[GPUImagePicture alloc] initWithImage:inputImage smoothlyScaleOutput:YES];
    }
    [staticPicture addTarget:filter];
    // blur is terminal filter
    if (hasBlur) {//水滴效果
        [filter addTarget:blurFilter];
        [blurFilter addTarget:self.imageFilter];
        //regular filter is terminal
    } else {
        [filter addTarget:self.imageFilter];
    }
    [staticPicture processImage];
}

- (void)doActionChangeFace:(id)sender {
    UIButton * btn=(UIButton*)sender;
    [btn setEnabled:NO];
    [stillCamera rotateCamera];
    
    m_is_front=!m_is_front;
    if (m_is_front) {
        [self.imageFilter setInputRotation:kGPUImageFlipHorizonal atIndex:0];
    } else {
        [self.imageFilter setInputRotation:kGPUImageNoRotation atIndex:0];
    }
    
    [btn setEnabled:YES];
}

- (void)doActionPigo:(id)sender {
    if([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera] && stillCamera && [stillCamera.inputCamera hasFlash]) {
        //设置闪光灯
        [self.flashToggleButton setEnabled:NO];
        [stillCamera.inputCamera lockForConfiguration:nil];
        
        if ([stillCamera.inputCamera flashMode] == AVCaptureFlashModeOff) {
            [stillCamera.inputCamera setFlashMode:AVCaptureFlashModeAuto];
            [self.flashToggleButton setImage:[UIImage imageNamed:@"flash-auto"] forState:UIControlStateNormal];
        }else if([stillCamera.inputCamera flashMode] == AVCaptureFlashModeAuto){
            [stillCamera.inputCamera setFlashMode:AVCaptureFlashModeOn];
            [self.flashToggleButton setImage:[UIImage imageNamed:@"flash"] forState:UIControlStateNormal];
        }else{
            [stillCamera.inputCamera setFlashMode:AVCaptureFlashModeOff];
            [self.flashToggleButton setImage:[UIImage imageNamed:@"flash-off"] forState:UIControlStateNormal];
        }
        
        [stillCamera.inputCamera unlockForConfiguration];
        [self.flashToggleButton setEnabled:YES];
    }
}

- (void)doActionClose:(id)sender {
    if (self.block_dismiss) {
        self.block_dismiss(0);
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)doActionSender:(id)sender
{
    if ([self.array_select count] < 1) {
        UIAlertView * alert_show = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"请拍摄照片!" delegate:nil cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
        [alert_show show];
        return;
    }
    //显示状态栏
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationNone];
    //进入上传页面
    {
        if (self.block_dismiss) {
            self.block_dismiss(1);
        }
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

- (void)doActionPicture:(UIButton*)sender {
    [sender setEnabled:NO];
    
    if (!isStatic) {
        
        if (self.array_select && [self.array_select count] > 8) {
            UIAlertView * alert_show = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"最多同时上传9张图片" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
            [alert_show show];
            
            [sender setEnabled:YES];
            return;
        }
        
        [stillCamera capturePhotoAsJPEGProcessedUpToFilter:filter withCompletionHandler:^(NSData *processedJPEG, NSError *error){
            UIImage * image = [UIImage imageWithData:processedJPEG];
            //save
            [image saveToAlbumWithMetadata:nil customAlbumName:nil completionBlock:^(NSURL *url) {
                //success
                NSLog(@"success");
                
                /*
                if (assetsLibrary_for_url==nil) {
                    assetsLibrary_for_url = [[ALAssetsLibrary alloc]init];
                }*/
                [self.assetsLibrary assetForURL:url resultBlock:^(ALAsset *asset) {
                    [self.array_select addObject:asset];
                    //ref
                    [m_collectionView reloadData];
                    
                    [sender setEnabled:YES];
                    /*
                     //显示状态栏
                     [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationNone];
                     //进入上传页面
                     SMAlbumSubmitViewController * vc = [[SMAlbumSubmitViewController alloc] init];
                     vc.array_select = self.array_select;
                     vc.array_list = self.array_list;
                     vc.block_dismiss = self.block_dismiss;
                     [self.navigationController pushViewController:vc animated:YES];
                     */
                } failureBlock:^(NSError *error) {
                    UIAlertView * alert_show = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"程序无访问相册权限(设置>隐私>照片,请进行设置)" delegate:nil cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
                    [alert_show show];
                    
                    [sender setEnabled:YES];
                }];
            } failureBlock:^(NSError *error) {
                NSLog(@"error");
                UIAlertView * alert_show = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"程序无访问相册权限(设置>隐私>照片,请进行设置)" delegate:nil cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
                [alert_show show];
                
                [sender setEnabled:YES];
            }];
        }];
    } else {
        //保存静态图片
        [sender setEnabled:YES];
    }
}

- (void)doActionTool:(id)sender {
    UIButton * btn = (UIButton*)sender;
    
    CGRect rect=self.scollview_filter_btn.frame;
    CGRect new_rect;
    if (btn.isSelected) {
        new_rect=CGRectMake(rect.origin.x, rect.origin.y-100, rect.size.width, rect.size.height);
    } else {
        new_rect=CGRectMake(rect.origin.x, rect.origin.y+100, rect.size.width, rect.size.height);
    }
    btn.selected=!btn.selected;
    
    [UIView animateWithDuration:0.5 animations:^{
        self.scollview_filter_btn.frame=new_rect;
    } completion:^(BOOL finished) {
        
    }];
}

#pragma mark -
#pragma mark UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //显示状态栏
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationNone];
    //进入上传页面
}

#pragma mark -
#pragma mark UICollectionViewDataSource, UICollectionViewDelegate

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section;
{
    return [self.array_select count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath;
{
    AlbumAddImageCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:ADD_GROUP_PICKER_CELL forIndexPath:indexPath];
    
    // load the image for this cell
    if (indexPath.row < [self.array_select count]) {
        ALAsset * object = [self.array_select objectAtIndex:indexPath.row];
        cell.image_thumb.image = [UIImage imageWithCGImage:object.thumbnail];
    } else {
        cell.image_thumb.image = [UIImage imageNamed:@"album_add_image.png"];
    }
    
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView
           viewForSupplementaryElementOfKind:(NSString *)kind
                                 atIndexPath:(NSIndexPath *)indexPath
{
    ALbumFooter *footer = nil;
    if([kind isEqual:UICollectionElementKindSectionFooter]){
        footer = [collectionView dequeueReusableSupplementaryViewOfKind:kind
                                                    withReuseIdentifier:@"ALbumAddImageFooter"
                                                           forIndexPath:indexPath];
        if ([self.array_select count]>16) {
            footer.label_num.text = [NSString stringWithFormat:@"%d张照片", [self.array_select count]];
        }
        //album_add_image@2x
    } else if([kind isEqual:UICollectionElementKindSectionHeader]) {
        ALbumHeader * header = [collectionView dequeueReusableSupplementaryViewOfKind:kind
                                                                  withReuseIdentifier:@"ALbumHeader"
                                                                         forIndexPath:indexPath];
        return header;
    }
    return footer;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath;
{
    NSLog(@"select index:%d", indexPath.row);
}

@end









@implementation ALbumAddImageFooter

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // 在此添加
        // 初始化时加载collectionCell.xib文件
        NSArray *arrayOfViews = [[NSBundle mainBundle] loadNibNamed:@"ALbumAddImageFooter" owner:self options: nil];
        // 如果路径不存在，return nil
        if(arrayOfViews.count < 1){return nil;}
        // 如果xib中view不属于UICollectionViewCell类，return nil
        if(![[arrayOfViews objectAtIndex:0] isKindOfClass:[UICollectionReusableView class]]){
            return nil;
        }
        // 加载nib
        self = [arrayOfViews objectAtIndex:0];
    }
    return self;
}

@end

@implementation AlbumAddImageCell

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // 在此添加
        // 初始化时加载collectionCell.xib文件
        NSArray *arrayOfViews = [[NSBundle mainBundle] loadNibNamed:@"AlbumAddImageCell" owner:self options: nil];
        // 如果路径不存在，return nil
        if(arrayOfViews.count < 1){return nil;}
        // 如果xib中view不属于UICollectionViewCell类，return nil
        if(![[arrayOfViews objectAtIndex:0] isKindOfClass:[UICollectionViewCell class]]){
            return nil;
        }
        // 加载nib
        self = [arrayOfViews objectAtIndex:0];
    }
    return self;
}

@end

@implementation AlbumTableCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {//85高
        self.backgroundColor=[UIColor clearColor];
        
        UIImageView * bg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"album_group_bg.png"]];
        bg.frame=CGRectMake(3, 3, 75, 75);
        [self addSubview:bg];
        
        _image_group = [[UIImageView alloc] initWithFrame:CGRectMake(6, 6, 70, 70)];
        [self addSubview:_image_group];
        
        _name = [[UILabel alloc] initWithFrame:CGRectMake(95, 16, 160, 30)];
        _name.textColor = [UIColor blackColor];
        _name.textAlignment=NSTextAlignmentLeft;
        _name.backgroundColor=[UIColor clearColor];
        [self addSubview:_name];
        
        _num = [[UILabel alloc] initWithFrame:CGRectMake(95, 46, 160, 30)];
        _num.textColor = [UIColor blackColor];
        _num.textAlignment=NSTextAlignmentLeft;
        _num.text=@"0";
        _num.backgroundColor=[UIColor clearColor];
        [self addSubview:_num];
        
        _btn_select = [[UIButton alloc] initWithFrame:CGRectMake(265, 27, 30, 30)];
        [_btn_select setImage:[UIImage imageNamed:@"album_list_selected_no.png"] forState:UIControlStateNormal];
        [_btn_select setImage:[UIImage imageNamed:@"album_list_selected.png"] forState:UIControlStateSelected];
        _btn_select.userInteractionEnabled=NO;
        [self addSubview:_btn_select];
        
        self.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    return self;
}

- (void)awakeFromNib
{
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];
    
    // Configure the view for the selected state
}

@end




@implementation UIImage(KIAddin)

- (void)saveToAlbumWithMetadata:(NSDictionary *)metadata
                customAlbumName:(NSString *)customAlbumName
                completionBlock:(void (^)(NSURL* url))completionBlock
                   failureBlock:(void (^)(NSError *error))failureBlock
{
    NSData * imageData = UIImageJPEGRepresentation(self, 1.0);
    ALAssetsLibrary * assetsLibrary = [[ALAssetsLibrary alloc] init];
    [assetsLibrary writeImageDataToSavedPhotosAlbum:imageData
                                           metadata:metadata
                                    completionBlock:^(NSURL *assetURL, NSError *error) {
                                        if (error) {
                                            if (failureBlock) {
                                                failureBlock(error);
                                            }
                                        } else {
                                            if (completionBlock) {
                                                completionBlock(assetURL);
                                            }
                                        }
                                    }];
}

- (UIImage *)fixOrientation {
    // No-op if the orientation is already correct
    if (self.imageOrientation == UIImageOrientationUp) return self;
    
    // We need to calculate the proper transformation to make the image upright.
    // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    switch (self.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, self.size.width, self.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, self.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, self.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        case UIImageOrientationUp:
        case UIImageOrientationUpMirrored:
            break;
    }
    
    switch (self.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, self.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, self.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        case UIImageOrientationUp:
        case UIImageOrientationDown:
        case UIImageOrientationLeft:
        case UIImageOrientationRight:
            break;
    }
    
    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, self.size.width, self.size.height,
                                             CGImageGetBitsPerComponent(self.CGImage), 0,
                                             CGImageGetColorSpace(self.CGImage),
                                             CGImageGetBitmapInfo(self.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (self.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,self.size.height,self.size.width), self.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,self.size.width,self.size.height), self.CGImage);
            break;
    }
    
    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}

@end





